package com.hustzp.com.xichuangzhu.me;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.FindCallback;
import com.hustzp.com.xichuangzhu.R;
import com.hustzp.com.xichuangzhu.dao.ReViewDao;
import com.hustzp.com.xichuangzhu.model.Review;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import in.srain.cube.views.loadmore.LoadMoreContainer;
import in.srain.cube.views.loadmore.LoadMoreHandler;
import in.srain.cube.views.loadmore.LoadMoreListViewContainer;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

/**
 * Created by Administrator on 2016/6/8.
 */
public class LikeQuoteFragment extends Fragment {

    View rootView = null;

    private PtrFrameLayout quotePtrFrameLayout;
    private LoadMoreListViewContainer quoteContainer;
    private List<Review> quotes = new ArrayList<>();
    private ListView quoteListView;
    private QuoteAdapter quoteAdapter;

    private int pageIndex = 1;
    private int pageSize = 15;

    private Map<Integer, AVObject> quoteObjs = new HashMap<>();
    private boolean isDelMode;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_like_quote, container, false);
            initViews();
        }

        return rootView;
    }

    private void initViews() {
        isDelMode = getArguments().getBoolean("isDelMode");

        quoteListView = (ListView) rootView.findViewById(R.id.list_view_quote);
        quoteAdapter = new QuoteAdapter(quotes);
        quoteListView.setAdapter(quoteAdapter);

        quotePtrFrameLayout = (PtrFrameLayout) rootView.findViewById(R.id.ptr_frame_quote);

        quotePtrFrameLayout.setLoadingMinTime(1000);
        quotePtrFrameLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, quoteListView, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                pageIndex = 1;
                loadQuotes(pageIndex, pageSize);
            }
        });

        quoteContainer = (LoadMoreListViewContainer) rootView.findViewById(R.id.container_quote);
        quoteContainer.useDefaultHeader();
        quoteContainer.setLoadMoreHandler(new LoadMoreHandler() {
            @Override
            public void onLoadMore(LoadMoreContainer loadMoreContainer) {
                //加载更多操作
                pageIndex++;
                loadQuotes(pageIndex, pageSize);
            }
        });
        loadQuotes(pageIndex, pageSize);
    }


    private void loadQuotes(final int pIndex, int pSize) {
        AVQuery query = AVQuery.getQuery("LikeQuote");
        query.setCachePolicy(AVQuery.CachePolicy.NETWORK_ELSE_CACHE);
        query.limit(pSize);
        query.skip((pIndex - 1) * pSize);
        query.whereEqualTo("user", AVUser.getCurrentUser());
        query.orderByDescending("createdAt");
        query.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if (list != null && !list.isEmpty()) {
                    if (pageIndex == 1) {
                        quotePtrFrameLayout.refreshComplete();
                        quotes.clear();
                        quoteObjs.clear();
                    }
                    List<Integer> quoteIds = new ArrayList<>();
                    for (AVObject avObj : list) {
                        quoteIds.add(avObj.getInt("quoteId"));
                        quoteObjs.put(avObj.getInt("quoteId"), avObj);
                    }

                    quotes.addAll(new ReViewDao(getContext()).getLikeQuotes(quoteIds));
                    quoteAdapter.notifyDataSetChanged();
                    quoteContainer.loadMoreFinish(false, true);
                } else {
                    pageIndex--;
                    quoteContainer.loadMoreFinish(false, false);
                }
            }
        });
    }

    class QuoteAdapter extends BaseAdapter {

        private List<Review> data;

        public QuoteAdapter(List data) {
            this.data = data;
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            QuoteViewHolder holder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_cust_quote_item, parent, false);
                holder = new QuoteViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (QuoteViewHolder) convertView.getTag();
            }

            final Review quote = data.get(position);
            holder.recmdTitle.setText(quote.getQuote());
            holder.recmdAuthor.setText(quote.getAuthor() + "《" + quote.getWork() + "》");
            if (isDelMode) {
                holder.delBtn.setVisibility(View.VISIBLE);
                holder.delBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        quoteObjs.get(quote.getId()).deleteInBackground(new DeleteCallback() {
                            @Override
                            public void done(AVException e) {
                                if (e == null) {
                                    data.remove(position);
                                    notifyDataSetChanged();
                                } else {
                                    Toast.makeText(getContext(), "删除失败，请重试", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                });
            } else {
                holder.delBtn.setVisibility(View.GONE);
            }


            return convertView;
        }

        class QuoteViewHolder {
            TextView recmdTitle;
            TextView recmdAuthor;
            ImageView delBtn;

            public QuoteViewHolder(View itemView) {
                recmdTitle = (TextView) itemView.findViewById(R.id.tv_quote);
                recmdAuthor = (TextView) itemView.findViewById(R.id.tv_author);
                delBtn = (ImageView) itemView.findViewById(R.id.del_btn);
            }
        }
    }
}
